package com.shioirikukuri.controller;

import com.shioirikukuri.dto.ComboDTO;
import com.shioirikukuri.service.IComboService;
import com.shioirikukuri.service.IFoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/combo")
public class ComboController {

	private static final String UPLOAD_DIR = "F:\\Study\\UniversityCourse\\NewThesis\\Program\\Front\\Administrator\\public\\combos\\";

	@Autowired
	private IComboService comboService;

	@Autowired
	private IFoodService foodService; // 注入Food服务

	/**
	 * 获取所有套餐全部信息
	 *
	 * @return 包含所有套餐全部信息的列表
	 */
	@GetMapping
	public ResponseEntity<List<ComboDTO>> getAllCombos() {
		return ResponseEntity.ok(comboService.getAllCombos());
	}


	/**
	 * 创建新套餐
	 *
	 * @param comboDTO 包含套餐详细信息的请求体
	 * @return 201状态码及新创建套餐的完整信息
	 */
	@PostMapping
	public ResponseEntity<?> createCombo(@RequestBody ComboDTO comboDTO) {
		try {
			// 调用服务层创建套餐
			ComboDTO createdCombo = comboService.createCombo(comboDTO);
			return new ResponseEntity<>(createdCombo, HttpStatus.CREATED);
		} catch (IllegalArgumentException e) {
			// 处理菜品不存在等业务异常
			return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
		} catch (Exception e) {
			// 处理其他异常
			return new ResponseEntity<>("Failed to create combo.", HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	/**
	 * 更新套餐信息（全量更新）
	 *
	 * @param id         目标套餐ID
	 * @param comboDTO   新的套餐数据
	 * @return 更新后的套餐完整信息
	 */
	@PutMapping("/{id}")
	public ResponseEntity<ComboDTO> updateCombo(@PathVariable Long id, @RequestBody ComboDTO comboDTO) {
		try {
			ComboDTO updatedCombo = comboService.updateCombo(id, comboDTO);
			return ResponseEntity.ok(updatedCombo);
		} catch (IllegalArgumentException e) {
			return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
		} catch (Exception e) {
			return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	/**
	 * 删除指定套餐（物理删除）
	 * @param id 套餐ID
	 * @return 204无内容响应
	 */
	@DeleteMapping("/{id}")
	public ResponseEntity<Void> deleteCombo(@PathVariable Long id) {
		comboService.deleteCombo(id);
		return ResponseEntity.noContent().build();
	}

	/**
	 * 处理套餐图片上传
	 * @param file 上传的图片文件
	 * @return 图片访问路径 或 错误信息
	 * @apiNote 安全特性：
	 *         - 生成唯一文件名防止覆盖
	 *         - 路径合法性校验防路径遍历攻击
	 */
	@PostMapping("/upload")
	public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) {
		try {
			if (file.isEmpty()) {
				return ResponseEntity.badRequest().body("Failed to upload. File is empty.");
			}

			// 创建基于当前日期和时间的文件名
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
			String fileName = sdf.format(new Date()) + "." + getExtension(file.getOriginalFilename());

			// 创建上传文件的目标路径
			Path filePath = Paths.get(UPLOAD_DIR).resolve(fileName).normalize();

			// 检查目标路径是否合法，防止越界访问
			if (!filePath.toFile().getParentFile().getCanonicalPath().equals(new File(UPLOAD_DIR).getCanonicalPath())) {
				return ResponseEntity.badRequest().body("Failed to upload. Invalid file path.");
			}

			// 将上传的文件保存到指定位置
			Files.copy(file.getInputStream(), filePath);

			// 返回图片的访问URL，假设前端可以通过相对路径访问静态资源
			String fileDownloadUri = "/combos/" + fileName;
			return ResponseEntity.ok(fileDownloadUri);
		} catch (IOException e) {
			return ResponseEntity.status(500).body("Could not upload the file: " + file.getOriginalFilename() + " => " + e.getMessage());
		}
	}

	// 辅助方法：获取文件扩展名
	private String getExtension(String filename) {
		if (filename == null) {
			return "";
		}
		int lastUnixPos = filename.lastIndexOf('/');
		int lastWindowsPos = filename.lastIndexOf('\\');
		int index = Math.max(lastUnixPos, lastWindowsPos);
		return filename.substring(index + 1).contains(".") ? filename.substring(filename.lastIndexOf('.') + 1) : "";
	}
}